<script setup>
import {cartListGetAPI, cartGameDeleteAPI, cartAddAPI, orderAddAPI, checkOrderExist, orderDeleteAPI} from "@/api/FrontApi/order.js";
import {ref, onMounted, onBeforeUnmount, computed} from "vue";
import FriendsList from "@/views/FrontViews/StoreModule/Cart/components/FriendsList.vue";
import defaultAvatar from '@/assets/images/default.png'
import {useRouter} from "vue-router";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";

// 获取购物车数据并封装
const getCartList = async () => {
  const res = await cartListGetAPI()
  if (res.code === 1) {
    orderInfo.value.orderGames = []
    res.data.map((item) => {
      const orderGame = ref({
        id: item.id,
        gameId: item.gameId,
        chineseName: item.chineseName,
        widerPicture: item.widerPicture,
        gamePrice: item.gamePrice,
        receive: null, // 接收的好友
        buyForType: 0 // 购买方式：为自己购买，给好友购买
      })
      orderInfo.value.orderGames.push(orderGame.value)
    })
  }
}

const isOrderExist = ref(false)
const checkOrder = async () => {
  const res = await checkOrderExist()
  if (res.code === 1) {
    if (res.data !== null) {
      isOrderExist.value = true
    } else {
      isOrderExist.value = false
    }
  }
}

onMounted(() => {
  getCartList()
  checkOrder()
  // 添加鼠标监听事件
  document.addEventListener("click", handleClickOutside);
})

// 组件销毁时也销毁鼠标监听事件
onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside)
});

// 控制下拉框
const isDropdownShow = ref(null)
const handleDropdownShow = (index) => {
  isDropdownShow.value = index
}

// 监听鼠标失焦时间，关闭下拉框
const handleClickOutside = (event) => {
  if (!event.target.closest('.to-who')) {
    isDropdownShow.value = null;
  }
}

// 订单信息
const orderInfo = ref({
  amount: null,
  payment: null,
  orderGames: []
})

// 为谁购买
const buyFor = (type, id) => {
  orderInfo.value.orderGames.forEach((item) => {
    if (item.id === id) {
      if (type === 0) {
        item.receive = null
      }
      item.buyForType = type
    }
  })
  isDropdownShow.value = null
}

// 计算总价
const totalAmount = computed(() => {
  const sum = orderInfo.value.orderGames.reduce((sum, game) => {
    const price = parseFloat(game.gamePrice.currentPrice) || 0
    return sum + price;
  }, 0)
  return sum.toFixed(2)
})

// 添加游戏
const addGame = async (gameId) => {
  const res = await cartAddAPI(gameId)
  if (res.code === 1) {
    getCartList()
  }
}

// 移除游戏
const removeGame = async (item) => {
  const res = await cartGameDeleteAPI([item.id])
  if (res.code === 1) {
    getCartList()
  }
}

// 打开好友列表
const isFriendsListShow = ref(false)
const selectId = ref(null)
const showFriendsList = (id) => {
  selectId.value = id
  isFriendsListShow.value = true;
}

// 选中的好友
const selectFriend = (item, selectId) => {
  orderInfo.value.orderGames.forEach((game) => {
    if (game.id === selectId) {
      game.receive = item
    }
  })
}

// 删除购物车中所有内容
const removeAllGames = async () => {
  const ids = orderInfo.value.orderGames.map(game => game.id)
  const res = await cartGameDeleteAPI(ids)
  if (res.code === 1) {
    getCartList()
  }
}
const router = useRouter()

// 跳转到支付
const addToOrder = async () => {
  const orderGames = orderInfo.value.orderGames.map(game => ({
    gameId: game.gameId,
    receiveId: game.receive ? game.receive.id : null
  }))
  const res = await orderAddAPI(orderGames)
  if (res.code === 1) {
    router.push('/pay')
  }
}

// 删除订单
const deleteOrder = async () => {
  const res = await orderDeleteAPI()
  if (res.code === 1) {
    ElMessage.success("删除成功")
    checkOrder()
  }
}
</script>

<template>
  <div class="cart-page">
    <div v-if="orderInfo.orderGames.length !== 0" class="container">
      <div class="games-container">
        <div class="games">
          <div v-for="(item, index) in orderInfo.orderGames" :key="index" class="game">
            <div class="game-info">
              <div class="wider-picture">
                <img @click="router.push(`/store/detail/${item.gameId}`)" :src="item.widerPicture">
              </div>
              <div class="game-detail">
                <div class="game-title">{{ item.chineseName }}</div>
                <div class="game-price-container">
                  <div class="game-price">
                    <template v-if="item.gamePrice.currentPrice === '0.00'">
                      免费开玩
                    </template>
                    <template v-else>
                      <template v-if="item.gamePrice.discount === 0">
                        ￥{{ item.gamePrice.originPrice }}
                      </template>
                      <template v-else>
                        <div class="discount">
                          <div class="discount-percent">-{{item.gamePrice.discount}}%</div>
                          <div class="discount-price">
                            <span class="discount-origin-price">￥{{ item.gamePrice.originPrice }}</span>
                            <span class="discount-current-price">￥{{ item.gamePrice.currentPrice }}</span>
                          </div>
                        </div>
                      </template>
                    </template>
                  </div>
                </div>
                <div class="game-option">
                  <div class="to-who">
                    <div @click.stop="handleDropdownShow(index)" class="current-item">
                      <span>{{ item.buyForType === 0 ? "用于我的账户" : "为好友购买" }}</span><i class="iconfont icon-a-xiala2"></i>
                    </div>
                    <div v-show="isDropdownShow === index" class="dropdown-menu">
                      <div @click="buyFor(0, item.id)">用于我的账户</div>
                      <div @click="buyFor(1, item.id)">为好友购买</div>
                    </div>
                  </div>
                  <div class="add-or-remove">
                    <span @click="addGame(item.gameId)">添加</span>
                    <span>|</span>
                    <span @click="removeGame(item)">移除</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-show="item.buyForType === 1" class="buy-for-friend">
              <div v-show="!item.receive" class="choose-friend">
                <button @click="showFriendsList(item.id)" class="choose-friends-button">选择礼物接收人...</button>
              </div>
              <div v-show="item.receive" class="to-friends">
                <span>礼物接收人:</span>
                <img :src="item.receive ? item.receive.avatar : defaultAvatar">
                <span>{{ item.receive ? item.receive.nickname : '' }}</span>
                <span @click="showFriendsList(item.id)">(编辑)</span>
              </div>
            </div>
          </div>
        </div>
        <div class="options">
          <div class="go-on-buy" @click="router.back()">继续购物</div>
          <div class="remove-all-games" @click="removeAllGames">移除所有游戏</div>
        </div>
        <div class="recommend"></div>
      </div>
      <div class="to-pay-container">
        <div class="not-in-order">
          <div class="count-price">
            <span>预计总额</span>
            <span>￥{{ totalAmount }}</span>
          </div>
          <div class="desc">如适用，销售税将在付款时进行结算</div>
          <div @click="addToOrder" class="go-to-pay">跳转至支付</div>
        </div>
        <div v-if="isOrderExist" class="in-order">
          <div class="desc">
            <div>您有一个待支付的订单</div>
            <div>如果您有一个新的订单，此订单会被覆盖</div>
          </div>
          <div class="options">
            <div class="go-pay" @click="router.push('/pay')">去支付</div>
            <div class="delete" @click="deleteOrder">删除订单</div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="no-data">
      <div class="desc">
        购物车中暂无数据<i class="iconfont icon-kongshuju"></i>
      </div>
      <div @click="router.push('/')" class="go-shopping">
        去购物
      </div>
    </div>
    <FriendsList v-model:isFriendsListShow="isFriendsListShow" v-model:selectId="selectId" @chooseFriend="selectFriend" />
  </div>
</template>

<style scoped lang="scss">
.cart-page {
  .container {
    width: 940px;
    display: flex;
    justify-content: space-between;
    .games-container {
      .games {
        display: flex;
        flex-direction: column;
        gap: 20px;
        .game {
          width: 615px;
          min-height: 123px;
          padding: 15px;
          background-color: rgba(0, 0, 0, .25);
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .game-info {
            display: flex;
            justify-content: space-between;
            .wider-picture {
              width: 200px;
              max-height: 150px;
              img {
                cursor: pointer;
              }
            }
            .game-detail {
              width: 370px;
              .game-title {
                font-size: 18px;
                line-height: 22px;
                color: #fff;
                font-weight: 500;
              }
              .game-price-container {
                margin-top: 8px;
                display: flex;
                justify-content: end;
                .game-price {
                  color: #fff;
                  font-size: 18px;
                  .discount {
                    height: 40px;
                    display: flex;
                    .discount-percent {
                      line-height: 34px;
                      text-align: center;
                      padding: 3px 5px;
                      background-color: $discountBackgroundColor;
                      color: $discountTextColor;
                      text-shadow: 1px 1px 4px rgba(0, 0, 0, 1);
                    }
                    .discount-price {
                      display: flex;
                      flex-direction: column;
                      text-align: center;
                      .discount-origin-price {
                        line-height: 18px;
                        font-size: 12px;
                        margin: 0 20px;
                        position: relative;
                        color: #738895;
                        &:before {
                          content: '';
                          left: 0;
                          right: 0;
                          position: absolute;
                          top: 43%;
                          border-bottom: 1.5px solid #738895;
                          transform: skewY(-8deg);
                          box-shadow: 0 0 2px black;
                        }
                      }
                      .discount-current-price {
                        line-height: 22px;
                        font-size: 18px;
                        padding: 0 4px 0 0;
                      }
                    }
                  }
                }
              }
              .game-option {
                margin-top: 8px;
                display: flex;
                justify-content: space-between;
                .to-who {
                  position: relative;
                  .current-item {
                    width: 130px;
                    height: 28px;
                    text-align: center;
                    cursor: pointer;
                    font-weight: 300;
                    border-radius: 3px;
                    background: rgba(59, 63, 72, .5);
                    line-height: 26px;
                    color: #dfe3e6;
                    font-size: 12px;
                  }
                  .dropdown-menu {
                    width: 130px;
                    background-color: #3D4450;
                    box-shadow: 0 0 2px #000000;
                    border-radius: 2px;
                    position: absolute;
                    color: #dcdedf;
                    div {
                      padding: 6px 16px;
                      font-size: 13px;
                      cursor: pointer;
                      &:hover {
                        background-color: #dcdedf;
                        color: #3D4450;
                      }
                    }
                  }
                  span {
                    margin-right: 8px;
                  }
                }
                .add-or-remove {
                  height: 28px;
                  line-height: 28px;
                  span {
                    color: #606f7f;
                    font-size: 12px;
                  }
                  span:nth-child(1),
                  span:nth-child(3){
                    cursor: pointer;
                    &:hover {
                      color: #dcdedf;
                      border-bottom: 2px solid #606f7f;
                    }
                  }
                  span:nth-child(2) {
                    margin: 0 6px;
                  }
                }
              }
            }
          }
          .buy-for-friend {
            .choose-friend {
              margin: 20px 0;
              .choose-friends-button {
                border: 0;
                line-height: 32px;
                width: 100%;
                background: linear-gradient(to right, #47bfff 0%, #1a44c2 60%);
                background-position: 25%;
                background-size: 330% 100%;
                text-align: center;
                color: #dfe3e6;
                font-size: 14px;
                border-radius: 2px;
                cursor: pointer;
                &:hover {
                  background: linear-gradient(to right, #59c5ff 0%, #2856e1 60%);
                  background-position: 25%;
                  background-size: 330% 100%;
                }
              }
            }
            .to-friends {
              margin: 20px 0;
              span {
                color: #c6d4df;
                &:nth-child(1) {
                  margin-right: 10px;
                }
                &:nth-child(3) {
                  margin-left: 8px;
                }
                &:nth-child(4) {
                  margin: 0 6px;
                  font-size: 12px;
                  color: #606f7f;
                  cursor: pointer;
                  &:hover {
                    color: #fff;
                  }
                }
              }
              img {
                width: 30px;
                height: 30px;
              }
            }
          }
        }
      }
      .options {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        .go-on-buy {
          width: 76px;
          height: 36px;
          line-height: 36px;
          text-align: center;
          border-radius: 2px;
          color: #dfe3e6;
          background: #3d4450;
          cursor: pointer;
          &:hover {
            color: #fff;
            background: #434b56;
          }
        }
        .remove-all-games {
          color: #606f7f;
          cursor: pointer;
          &:hover {
            color: #fff;
          }
        }
      }
    }
    .to-pay-container {
      color: #fff;
      .not-in-order {
        padding: 15px;
        background-color: rgba(0, 0, 0, .25);
        .count-price {
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          span:last-child {
            font-size: 15px;
            color: #fff;
            font-weight: 700;
          }
        }
        .desc {
          margin: 10px 0;
          color: #ccd5e0;
          font-size: 12px;
        }
        .go-to-pay {
          width: 100%;
          height: 30px;
          line-height: 30px;
          text-align: center;
          background-color: #fff;
          background: linear-gradient(to right, #47bfff 0%, #1a44c2 60%);
          background-position: 25%;
          background-size: 330% 100%;
          border-radius: 2px;
          cursor: pointer;
          &:hover {
            background: linear-gradient(to right, #59c5ff 0%, #2856e1 60%);
            background-position: 25%;
            background-size: 330% 100%;
          }
        }
      }
      .in-order {
        margin-top: 20px;
        padding: 15px;
        background-color: rgba(0, 0, 0, .25);
        .desc {
          div:last-child {
            color: #ccd5e0;
            font-size: 12px;
          }
        }
        .options {
          .go-pay {
            margin-top: 12px;
            width: 100%;
            height: 30px;
            line-height: 30px;
            text-align: center;
            color: #fff;
            background: linear-gradient(to right, #47bfff 0%, #1a44c2 60%);
            background-position: 25%;
            background-size: 330% 100%;
            border-radius: 2px;
            cursor: pointer;
            &:hover {
              background: linear-gradient(to right, #59c5ff 0%, #2856e1 60%);
              background-position: 25%;
              background-size: 330% 100%;
            }
          }
          .delete {
            margin-top: 12px;
            width: 100%;
            height: 30px;
            line-height: 30px;
            text-align: center;
            color: #fff;
            background: linear-gradient(to right, #ff3370 0%, #ff001e 60%);
            background-position: 25%;
            background-size: 330% 100%;
            border-radius: 2px;
            cursor: pointer;
            &:hover {
              background: linear-gradient(to right, #ff2362 0%, #e5001a 60%);
              background-position: 25%;
              background-size: 330% 100%;
            }
          }
        }
      }
    }
  }
  .no-data {
    margin: 0 auto;
    text-align: center;
    width: 940px;
    font-size: 30px;
    color: #ababab;
    display: flex;
    flex-direction: column;
    align-items: center;
    .desc {
      padding-top: 30px;
      i {
        margin-left: 20px;
        font-size: 30px;
      }
    }
    .go-shopping {
      font-size: 26px;
      cursor: pointer;
      &:hover {
        font-size: $themeColor;
        border-bottom: 2px solid $themeColor;
        color: $themeColor;
      }
    }
  }
}
</style>
